package com.cat.binaryTree;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/longest-univalue-path/description/
 * @create 2025/9/14 18:50
 * @since JDK17
 */

public class Solution38 {
    int res;
    int f(TreeNode root, int cur) {
        if (root == null) {
            return 0;
        }
        int l = f(root.left, root.val);
        int r = f(root.right, root.val);
        int ans = root.val == cur ? 1 : 0;
        if (root.left == null || root.left.val != root.val) {
            l = 0;
        }
        if (root.right == null || root.right.val != root.val) {
            r = 0;
        }
        res = Math.max(res, ans + l + r);
        return ans + Math.max(l, r);
    }
    public int longestUnivaluePath(TreeNode root) {
        f(root, Integer.MIN_VALUE);
        return res;
    }
}
